package com.bjc.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program: nettypro
 * @description: 一个buffer双向读取写入
 * @author: bjc
 * @create: 2021-09-03 21:09
 */
public class NIOFileChannel03 {

    public static void main(String[] args) throws Exception{
        FileInputStream fileInputStream = new FileInputStream("D:\\iotest_delete\\1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("D:\\iotest_delete\\2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true){
            // 这里有个重要的动作  清空buffer   如果这里没有  那么limit == position = 0
            byteBuffer.clear();
            int read = fileChannel01.read(byteBuffer);
            System.out.println("read= "+read);
            if (read==-1){
                break;
            }
            //将buffer中的数据写入到fileChannel02---》2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }
        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
